
settingsURL = 'https://wallboard-notifier.googlecode.com/git/images/settings.png';
keyboardURL = 'https://wallboard-notifier.googlecode.com/git/images/keyboard.jpg';
phoneURL = 'https://wallboard-notifier.googlecode.com/git/images/phone.png';
cssURL = 'https://wallboard-notifier.googlecode.com/git/chatAlert/chatAlert.css';

function goBabyGo(){
	console.log("goBabyGo!");
	//console.log(localStorage.retrievedChatQueues);
	if ( ! localStorage.retrievedChatQueues ) {
		console.log("hopefully about to reset");
		alert('Might be a bug in chatAlert.js. About to reset your settings to 0.');
		resetMe();
	}else {
		retrievedChatQueues = JSON.parse(localStorage.getItem('retrievedChatQueues'));
	}
	checkDisplayed();
	createHTML();
	initializeHTML();
}

function notifier(img, title, text) {
	/*
	Designed to be the single notifier function, then just change the img, title, text variables as needed.
	*/
	var havePermission = window.webkitNotifications.checkPermission();
	
	if (havePermission == 0) {
   		// 0 is PERMISSION_ALLOWED
   		var notification = window.webkitNotifications.createNotification(img,title,text);

    	notification.onclick = function () { notification.cancel();	} //clicking the notification makes it go away (may remove later)
   		
   		notification.show();
   		
   		setTimeout( function(){notification.cancel()},15000); //go away after 15 seconds
  		
  	} 
	else {
		alert("The notifier won't work as it hasn't got permission");
  	}
}  

function resetMe() {
	/*
	This thing should:
		-clear localStorage
		-initialize retrievedChatQueues from the default
		-Set all HTML elements back to their default state
	*/
	console.log("resetMe");

	//set defaults for those properties
	var maxCall = 50;
	var maxWait = 60;
	var maxLong = 20;
	sliderDef = 0; //where the sliders should be set by default (0 = off)
		
	localStorage.clear();

	retrievedChatQueues = { 
		"support":{"pretty_name":"Support",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"l2":{"pretty_name":"L2",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"reseller":{"pretty_name":"Reseller",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"l3":{"pretty_name":"L3 (Escalation)",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"sales":{"pretty_name":"Sales",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"verification":{"pretty_name":"Verifiers",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"saves":{"pretty_name":"saves",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"tos":{"pretty_name":"ToS",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"billing":{"pretty_name":"Billing",		
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"chargebacks":{"pretty_name":"Chargebacks",	
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"fraud":{"pretty_name":"Fraud",			
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"b2":{"pretty_name":"B2",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"b3":{"pretty_name":"B3",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"sitecompatibility":{"pretty_name":"Site Compat",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"qa":{"pretty_name":"QA",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"lineitems":{"pretty_name":"Lineitems",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"domains":{"pretty_name":"Domains",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"renewals":{"pretty_name":"renewals",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1},
		
		"dedicated":{"pretty_name":"dedicated",
			"displayed":false,"is_enabled":false,"callSlider":sliderDef,"callSliderEnabled":false,"waitSlider":sliderDef,"waitSliderEnabled":false,"longSlider":sliderDef,"longSliderEnabled":false,"maxCall":maxCall,"maxWait":maxWait,"maxLong":maxLong,"timestamp":0,"timeframe":1}
		}

	localStorage.retrievedChatQueues = JSON.stringify(retrievedChatQueues);
	initializeHTML();
}

function basicNotify (e) {


	if (e.target.id){ //ONLY continue IF my target ID even exists (otherwise it means it found something other than a queue)
	
		
		

		var objectID = e.target.id.slice(6); //get a variable for my object name
		var myObject = retrievedChatQueues[objectID];

		if (myObject){ //make sure the object even exists, otherwise I don't want to continue. 

				
			if (myObject.displayed == true){ //make sure the object is set to display
				//console.log('displayed:',objectID); //success

				//if (myObject.is_enabled == true){

					if ((Math.round(Date.now())/1000) - myObject.timestamp > 60){
						
						var calls = parseInt(e.target.children[0].children[0].children[1].children[0].innerHTML);
						//console.log(objectID+'calls'+calls);

						//var wait = parseInt(e.target.children[0].children[0].children[1].children[0].innerHTML.slice(0,2));
						var fullWait = e.target.children[0].children[0].children[2].children[0].innerHTML;
						var wait = parseInt(fullWait.slice(0,2));
						//console.log(objectID+'wait'+wait);

						//var longs = parseInt(e.target.children[0].children[0].children[2].children[0].children[0].children[0].children[1].children[3].innerHTML);



						//console.log(calls);
						if (myObject.callSliderEnabled && calls >= myObject.callSlider){ //if queue something is over a threshold then notify
							//console.log('calls',objectID);
							notifyTitle = myObject.pretty_name+' > '+calls;
							notifyImg = keyboardURL;
							notifyText = 'Wait: '+fullWait;
							notifier(notifyImg,notifyTitle,notifyText);
							myObject.timestamp = Math.round(Date.now()/1000);

						} else if (myObject.waitSliderEnabled && wait >= myObject.waitSlider) {
							//console.log('wait',objectID);
							notifyTitle = myObject.pretty_name+' wait time > '+fullWait;
							notifyImg = keyboardURL;
							notifyText = 'Queue: '+calls;
							notifier(notifyImg,notifyTitle,notifyText);
							myObject.timestamp = Math.round(Date.now()/1000);
							//set the title, image, message
						} 
						//notifier(notifyImg,notifyTitle,notifyText);

					}
				//}
			}
		}
	} 
	
}


function adjustThreshold() {
	/*
	When the slider is adjusted, this will: 
		-Update the span
		-Update the object
		-Save the object to localStorage
	*/
	console.log('adjustThreshold');
	//set vars
	var objectID = this.id.slice(0,-11);
	var defineSpan = '_'+this.id.slice(-10,-6)+'SliderSpan';
	var spanID = objectID+defineSpan;
	var sliderEnabled = this.id.slice(-10,-6)+'SliderEnabled';
	
	//update span
	document.getElementById(spanID).innerHTML = this.value;

	//update object
	paramID = this.id.slice(-10,-6)+'Slider';
	retrievedChatQueues[objectID][paramID] = this.value;

	//check for zeros & disable if zero is set
	if (this.value == 0){
		//say so
		console.log(spanID);
		console.log(objectID+' at zero');
		retrievedChatQueues[objectID][sliderEnabled] = false;
	} else {
		retrievedChatQueues[objectID][sliderEnabled] = true;
	}

	//save object to local storage
	localStorage.retrievedChatQueues = JSON.stringify(retrievedChatQueues);

}

/*
function disableThreshold(){
	console.log('disableThreshold');
	var mySliders = document.getElementsByClassName('slider');

	for (var i = 0; i < mySliders.length; i++){
		var objectID = mySliders[i];
		if (mySliders[i].value == 0){
			console.log(mySliders[i].id+' is at zero');
			//disable that crap
			retrievedChatQueues[objectID].
		}


	}


}
*/
function adjustStatus() {
	/*
	When the checkbox is changed, this will:
		-update the object
		-save the object to localStorage
		-possibly blur, colorize or something to a the div, feedback that it's not available / active.
		-Also maybe add new spans next to the titles of each queue on the board saying [active] or [inactive]
	*/
	objectID = this.id.slice(0,-9);
	if (this.checked == true) {
		retrievedChatQueues[objectID].is_enabled = true;
	}else{
		retrievedChatQueues[objectID].is_enabled = false;
	}
	localStorage.retrievedChatQueues = JSON.stringify(retrievedChatQueues);
}


function hideShow(){
	//console.log("stuff");
	var myControls = document.getElementById('controls');
	var button = document.getElementById('bfb_button')
	if (myControls.getAttribute('class') != 'hidden') {
		myControls.setAttribute('class','hidden');
		button.setAttribute('class','deselected');

	} else { 
		myControls.setAttribute('class','shown');
		button.setAttribute('class','selected');
	}
}

function addCSS(){
	var mylink = document.createElement('link');
	mylink.setAttribute("rel", "stylesheet");
	mylink.setAttribute("type", "text/css");
	mylink.setAttribute("href", cssURL);
	document.head.appendChild(mylink);
}	



function initializeHTML() {
	/*
	Sets all of my spans and sliders to their default state, need to do checkboxes too. 
	*/
	var mySliders = document.getElementsByClassName('slider');
	var mySpans = document.getElementsByClassName('sliderSpan');
	var myCheckboxes = document.getElementsByClassName('checkbox');
	for (var i = 0; i < mySliders .length; i++) {

		//set sliders to whatever is in the default object.
  			
		var objectID = mySliders[i].id.slice(0,-11);
		var objectProperty = mySliders[i].id.slice(-10);
		//console.log(objectID,objectProperty);

		mySliders[i].value = retrievedChatQueues[objectID][objectProperty];

		mySpans[i].innerHTML = retrievedChatQueues[objectID][objectProperty];
	}
	/*
	for (var i = 0; i < myCheckboxes.length; i++){
		//console.log(myCheckboxes[i]);
		myCheckboxes[i].checked = retrievedChatQueues[objectID].is_enabled;
	}
	*/

}

function checkDisplayed() {
	console.log('checkDisplayed');
	for (var i in retrievedChatQueues) { 
		//console.log('i',i);
		var displayedQueues = document.getElementById('queue_'+i);
		
		//console.log('all',i);

		if (displayedQueues.style.display != 'none'){
			//console.log('yesdisplay:',displayedQueues.id)
			retrievedChatQueues[i].displayed = true;
		}else {
			//console.log('nodisplay:',displayedQueues.id)
			retrievedChatQueues[i].displayed = false;
		}
	}

}

function createHTML () {
console.log('createHTML');

	var bfb = document.createElement('div');
	bfb.setAttribute('id','bfb');
	//bfb.setAttribute('class','off');
	bfb.innerHTML = '<button id="bfb_button" class="off"></button>';
	bfb.addEventListener('click',hideShow);
	document.body.appendChild(bfb);

	document.getElementById("bfb_button").addEventListener("click",function() { //So that I can check for permission
		if (window.webkitNotifications.checkPermission() != 0) {
			window.webkitNotifications.requestPermission();
		} 
	});
		
	var controls = document.createElement('div');
	controls.setAttribute('id','controls');
	controls.setAttribute('class','hidden');
	document.body.appendChild(controls);
		
	//first pull retrievedChatQueues from storage.

	for (var i in retrievedChatQueues) { 
		//console.log("in for loop");

		if (retrievedChatQueues[i].displayed == true){
		
			var br = document.createElement('br');

			var queueControlDiv = document.createElement('div');
			queueControlDiv.setAttribute('id',i+'_control');
			queueControlDiv.setAttribute('class','control');

			//Create checkboxes
			/*
			var controlCheckbox = document.createElement('input');
			controlCheckbox.setAttribute('type','checkbox');
			controlCheckbox.checked=retrievedChatQueues[i].is_enabled;
			controlCheckbox.setAttribute('id',i+'_checkbox'); //slap an ID on that sucker
			controlCheckbox.setAttribute('class','checkbox');
			controlCheckbox.addEventListener('click',adjustStatus);
			queueControlDiv.appendChild(controlCheckbox);
			*/

			var controlLabel = document.createElement('label');
			controlLabel.setAttribute('id',i+'_label');
			controlLabel.setAttribute('class','controlLabel');
			//controlLabel.setAttribute('class','generalLabel');
			controlLabel.innerHTML = retrievedChatQueues[i].pretty_name;
			queueControlDiv.appendChild(controlLabel);

			queueControlDiv.appendChild(document.createElement('br'));

			var callDiv = document.createElement('div');
			callDiv.setAttribute('id',i+'_call');
			queueControlDiv.appendChild(callDiv);


				var callSliderLabel = document.createElement('label');
				callSliderLabel.setAttribute('id',i+'_callSliderLabel');
				callSliderLabel.setAttribute('class','sliderLabel');
				callSliderLabel.setAttribute('class','generalLabel');
				callSliderLabel.innerHTML = 'Chats';
				callDiv.appendChild(callSliderLabel);

				var callSlider = document.createElement('input');
				callSlider.setAttribute('id',i+'_callSlider');
				callSlider.setAttribute('class','slider');
				callSlider.setAttribute('type','range');
				callSlider.setAttribute('min','sliderDef');
				callSlider.setAttribute('max',retrievedChatQueues[i].maxCall);
				callSlider.value = retrievedChatQueues[i].callSlider;
				callSlider.setAttribute('step','1');
				callSlider.addEventListener('change',adjustThreshold); //////listener
				callDiv.appendChild(callSlider);

				var callSliderSpan = document.createElement('span');
				callSliderSpan.setAttribute('id',i+'_callSliderSpan');
				callSliderSpan.setAttribute('class','sliderSpan');
				callSliderSpan.innerHTML = retrievedChatQueues[i].callSlider;
				callDiv.appendChild(callSliderSpan);

			var waitDiv = document.createElement('div');
			waitDiv.setAttribute('id',i+'_wait');
			queueControlDiv.appendChild(waitDiv);

				var waitSliderLabel = document.createElement('label');
				waitSliderLabel.setAttribute('id',i+'_waitSliderLabel');
				waitSliderLabel.setAttribute('class','sliderLabel');
				waitSliderLabel.setAttribute('class','generalLabel');
				waitSliderLabel.innerHTML = 'Longest Wait';
				waitDiv.appendChild(waitSliderLabel);

				var waitSlider = document.createElement('input');
				waitSlider.setAttribute('id',i+'_waitSlider');
				waitSlider.setAttribute('class','slider');
				waitSlider.setAttribute('type','range');
				waitSlider.setAttribute('min','sliderDef');
				waitSlider.setAttribute('max',retrievedChatQueues[i].maxWait);
				waitSlider.value = retrievedChatQueues[i].waitSlider;
				waitSlider.setAttribute('step','');
				waitSlider.addEventListener('change',adjustThreshold); //////listener
				waitDiv.appendChild(waitSlider);

				var waitSliderSpan = document.createElement('span');
				waitSliderSpan.setAttribute('id',i+'_waitSliderSpan');
				waitSliderSpan.setAttribute('class','sliderSpan');
				waitSliderSpan.innerHTML = retrievedChatQueues[i].longSlider;
				waitDiv.appendChild(waitSliderSpan);


			document.getElementById('controls').appendChild(queueControlDiv);
			document.getElementById('controls').appendChild(br);


		}
		
	}

	var resetButton = document.createElement('button');
	resetButton.setAttribute('id','resetButton');
	resetButton.innerHTML = 'reset';
	resetButton.addEventListener('click',resetMe);
	document.getElementById('controls').appendChild(resetButton);

	var wallboard = document.getElementById('wallboard');
	wallboard.addEventListener("DOMNodeInserted",function(e) {basicNotify(e)});
	
	addCSS();
}

function isReady() {
	//console.log("isReady()");
	if (document.getElementById('queue_sitecompatibility')) goBabyGo();
	else setTimeout(isReady,200);
}

	isReady();
